package com.yusi.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yusi.entity.City;
import com.yusi.entity.dto.GetCity;
import com.yusi.entity.dto.GetCity2;
import com.yusi.entity.dto.RespBean;
import com.yusi.service.ICityService;
import com.yusi.util.FieldEmptyValidator;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yusi
 * @since 2022-01-07
 */
@RestController
@RequestMapping("/air/path")
public class CityController {

    @Autowired
    private ICityService iCityService;

    @ApiOperation("新增机场")
    @PostMapping("/")
    @Transactional
    public RespBean setCity(@RequestBody City city){
        if (new FieldEmptyValidator().hasNullOrEmptyField(city)){
            RespBean.error("添加失败！请填写完整!");
        }
        if (iCityService.save(city)){
            return RespBean.success("新增机场成功！");
        }
        return RespBean.error("新增机场失败！");
    }

    @ApiOperation("删除机场")
    @DeleteMapping("/{id}")
    @Transactional
    public RespBean delCity(@PathVariable Integer id){
        if (iCityService.removeById(id)){
            return RespBean.success("删除成功！");
        }
        return RespBean.error("删除失败！");
    }
    @ApiOperation("修改机场")
    @PutMapping("/")
    @Transactional
    public RespBean updCity(@RequestBody City city){
        if (iCityService.updateById(city)){
            return RespBean.success("修改成功！");
        }
        return RespBean.error("修改失败！");
    }
    @ApiOperation("获取所有的机场")
    @GetMapping("/")
    public List<City> getCity(String name){
        if (!StringUtils.isEmpty(name)) {
            return iCityService.list(new QueryWrapper<City>().eq("city", name));
        }
        return iCityService.list();
    }
    @ApiOperation("按格式获取所有的机场")
    @GetMapping("/city")
    public List<GetCity> getCities(){
        List<City> list = iCityService.list(new QueryWrapper<City>().orderByAsc("city"));
        List<GetCity> getCities = new ArrayList<>();
        for (City c:list) {
            getCities.add(new GetCity().setLabel(c.getCity()+c.getAirportName()).setValue(c.getId()));
        }
        return getCities;
    }
    @ApiOperation("按格式获取所有的机场")
    @GetMapping("/city2")
    public List<GetCity2> getCities2(){
        List<City> list = iCityService.list(new QueryWrapper<City>().orderByAsc("city"));
        List<GetCity2> getCities = new ArrayList<>();
        for (City c:list) {
            getCities.add(new GetCity2().setLabel(c.getCity()+c.getAirportName()).setValue(c.getCity()+c.getAirportName()));
        }
        return getCities;
    }
}
